/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package severdorhttpsimples;

/**
 *
 * @author Alisson
 */
import java.io.*;
import java.net.*;
import utils.request.Request;
import utils.response.Response;
import utils.response.ResponseFactory;

public class WebServer {

    private static String BaseDir = "D:/Alisson/";

    public static String getBaseDir() {
        return BaseDir;
    }

    public static void main(String argv[]) throws Exception
    {
        //Primeira linha da mensagem de pedido HTTP e Nome do arquivo solicitado

        String requestMessageLine;

        //Aguarda conexão do cliente
        int port = 6789;
        //String host = "localhost";

        ServerSocket listenSocket = new ServerSocket(port); //, 1, InetAddress.getByName(host));
        while (true){
        Socket connectionSocket = listenSocket.accept();

        //Cria fluxo de Entrada

        BufferedReader inFromClient =
                new BufferedReader(new InputStreamReader(
                connectionSocket.getInputStream()));

        //Cria fluxo de Saída

        DataOutputStream outToClient =
                new DataOutputStream(
                connectionSocket.getOutputStream());

        //Lê a primeira linha do pedido HTTP que deveria ter o seguinte formato:
        //GET file_name HTTP/1.0

        requestMessageLine = inFromClient.readLine();

        //Examina a primeira linha da mensagem para extrair o nome do arquivo

        /*StringTokenizer tokenizedLine =
        new StringTokenizer(requestMessageLine);*/
        Request request = new Request();
	request.parse(requestMessageLine);
        Response response = ResponseFactory.createResponse(request);
        outToClient.write(response.respond().getBytes());
        outToClient.write(response.getReturnFile());

        // Fecha a conexão
        connectionSocket.close();
        }
    }
}
